package pers.jason.wppm.auth.web.controller;

import java.util.List;

import lombok.extern.log4j.Log4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.jason.wppm.api.support.ResultView;

/**
 * 
 * @author Jason
 * @Date 2018-10-26 09:56
 *
 */
@Log4j
@ControllerAdvice
public class ControllerExceptionHandler {


	/**
	 * 处理controller异常
	 * @param ex
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler()
	public ResultView handlerUserNotExistException(Exception ex) {
		ex.printStackTrace();
		log.info("异常信息：" + ex.getMessage());
		ResultView resultView = ResultView.failure(ex.getMessage());
		return resultView;
	}


	/**
	 * 处理WEB校验异常
	 * @param e
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(BindException.class)
	public ResultView  handleMethodArgumentNotValidException(BindException e){
		log.info("异常信息：" + e.getMessage());
		StringBuilder stringBuilder = new StringBuilder();
		List<ObjectError> errors = e.getBindingResult().getAllErrors();
		for(ObjectError objectError : errors) {
			stringBuilder.append(objectError.getDefaultMessage() + ";");
		}
		ResultView resultView = ResultView.failure(stringBuilder.toString());
		return resultView;
	}

	
}
